<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Install\Command;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Contract\ConfigInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\User\Contract\UserContract;
use Psr\Container\ContainerInterface;
use Qbhy\HyperfAuth\AuthManager;
use Symfony\Component\Console\Input\InputArgument;

/**
 * @Command
 */
class MySQLImportCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var AuthManager
     */
    protected $authManager;

    /**
     * @Inject
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @var UserContract
     */
    protected $userService;

    /**
     * @var string sql安装文件
     */
    protected $sqlFile;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('mysql:import');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('MySQL数据库导入');
        $this->addArgument('filename', InputArgument::REQUIRED, '文件名称');
    }

    public function handle(): void
    {
        try {
            $filename = trim($this->input->getArgument('filename'));
            $this->mysqlDataImport($filename);
            $this->line('导入SQL文件成功', 'info');
        } catch (\Exception $e) {
            $this->warn('导入SQL文件失败，错误：' . $e->getMessage());
        }
    }

    private function mysqlDataImport(string $filename): void
    {
        $version = Db::select('select VERSION() AS version;');
        $version = empty($version[0]->version) ? 5.6 : (float) $version[0]->version;
        if ($version < 5.7) {
            throw new \RuntimeException('mysql版本号错误，需要版本号 >= 5.7');
        }

        $this->sqlFile = BASE_PATH . '/storage/install/' . $filename . '.sql';
        if (! file_exists($this->sqlFile)) {
            throw new \RuntimeException('未找到导入SQL文件：' . $this->sqlFile);
        }

        $sqlArr = explode(';', file_get_contents($this->sqlFile));
        foreach ($sqlArr as $item) {
            $item = trim($item);
            if (empty($item)) {
                continue;
            }
            Db::statement((string) Db::raw($item . ';'));
        }
    }
}
